import React, {FC, useCallback, useMemo} from "react";
import "./css/CTablePreview.less";
import {isFunction} from "../../utils";
import {isDatasetFn, previewFile} from "../../services/PreviewService.tsx";
import {getLinkClickByKey} from "../../services/LinkClickService.tsx";

interface CTablePreviewProps {
    value: string,
    typeField: string,
    fileIdField: string,
    suffixField: string,
    isShowVersion: boolean,
    linkFun: string,
    linkComProps?: any
    data: any
}

const CTablePreview: FC<CTablePreviewProps> = (props: any) => {

    const handleClick: Function = useCallback(() => {
        // 如何有拓展方法这在点击之前调用该方法
        if (props.linkFun) {
            let fun: Function = getLinkClickByKey(props.linkFun);
            if (isFunction(fun)) {
                props.linkComProps ? fun(props.data, props.linkComProps) : fun(props.data)
            }
        }
        previewFile(props.data, {
            fileIdField: props.fileIdField,
            suffixField: props.suffixField
        });
    }, [props])

    const renderLink = useMemo(() => {
        const {value, data = {}, suffixField = "extName"}: {
            value: string,
            data: any,
            suffixField: string,
        } = props;

        if (data[suffixField] && isDatasetFn(data[suffixField])) {
            return <span className="sf_core_preview_link_value" onClick={handleClick}
                         title={value}>{value}</span>
        }
        return (<span title={value}>{value}</span>)
    }, [props])

    const renderCTablePreview = useMemo(() => {
        return (<div className="sf_core_preview_link">
            {renderLink}
        </div>)
    }, [props]);
    return (renderCTablePreview)
}

export default React.memo(CTablePreview);